<!-- components/charts/LineChart.vue -->
<template>
  <div ref="chartDom" class="chart-dom"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import { useElementSize } from '@vueuse/core'

const props = defineProps<{
  data: { accuracy: any[], loss: any[] }
}>()

const chartDom = ref<HTMLElement>()
let chart: echarts.ECharts | null = null

const { width, height } = useElementSize(chartDom)

onMounted(() => {
  if (!chartDom.value) return
  chart = echarts.init(chartDom.value)
  renderChart()
})

watch([() => props.data, width, height], () => {
  renderChart()
})

function renderChart() {
  if (!chart) return

  const option = {
    tooltip: { trigger: 'axis' },
    legend: { data: ['准确率', '损失值'] },
    xAxis: {
      type: 'category',
      data: props.data.accuracy.map(item => item.time)
    },
    yAxis: { type: 'value' },
    series: [
      {
        name: '准确率',
        type: 'line',
        data: props.data.accuracy.map(item => item.value),
        smooth: true,
        lineStyle: { color: '#409EFF' }
      },
      {
        name: '损失值',
        type: 'line',
        data: props.data.loss.map(item => item.value),
        smooth: true,
        lineStyle: { color: '#E6A23C' }
      }
    ]
  }

  chart.setOption(option)
}
</script>

<style scoped>
.chart-dom {
  width: 100%;
  height: 400px;
}
</style>